package com.bj.dz.service.impl;

import com.bj.dz.constant.Constant;
import com.bj.dz.entity.ReleaseTask;
import com.bj.dz.entity.TaskRecord;
import com.bj.dz.mapper.ReleaseSubtaskMapper;
import com.bj.dz.mapper.ReleaseTaskMapper;
import com.bj.dz.mapper.TaskRecordMapper;
import com.bj.dz.service.ReleaseTaskService;
import com.bj.dz.util.Constants;
import com.bj.dz.util.EmptyUtils;
import com.bj.dz.util.Page;
import com.sun.prism.shader.DrawSemiRoundRect_Color_AlphaTest_Loader;
import lombok.extern.slf4j.Slf4j;
import org.apache.jasper.security.SecurityUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ReleaseTaskServiceImpl implements ReleaseTaskService {

    @Resource
    private ReleaseTaskMapper releaseTaskMapper;
    @Resource
    private ReleaseSubtaskMapper releaseSubtaskMapper;
    @Resource
    private TaskRecordMapper taskRecordMapper;

    public ReleaseTask getReleaseTaskById(Integer id) {
        return releaseTaskMapper.getReleaseTaskById(id);
    }

    public List<ReleaseTask> getReleaseTaskListByMap(Map<String, Object> param) {
        return releaseTaskMapper.getReleaseTaskListByMap(param);
    }

    public Integer getReleaseTaskCountByMap(Map<String, Object> param) {
        return releaseTaskMapper.getReleaseTaskCountByMap(param);
    }

    @Transactional
    public boolean addReleaseTask(ReleaseTask releaseTask) {
        return releaseTaskMapper.insertReleaseTask(releaseTask) > 0 ? true : false;
    }

    @Transactional
    public boolean modifyReleaseTask(ReleaseTask releaseTask) {
        return releaseTaskMapper.updateReleaseTask(releaseTask) > 0 ? true : false;
    }

    @Transactional
    public boolean deleteReleaseTaskById(Integer id) {
        releaseSubtaskMapper.deleteReleaseSubtaskByType(id);
        return releaseTaskMapper.deleteReleaseTaskById(id) > 0 ? true : false;
    }

    public Page<ReleaseTask> queryReleaseTaskPageByMap(Map<String, Object> param, Integer pageNo, Integer pageSize) {
        Integer total = releaseTaskMapper.getReleaseTaskCountByMap(param);
        pageNo = EmptyUtils.isEmpty(pageNo) ? Constants.DEFAULT_PAGE_NO : pageNo;
        pageSize = EmptyUtils.isEmpty(pageSize) ? Constants.DEFAULT_PAGE_SIZE : pageSize;
        Page page = new Page(pageNo, pageSize, total);
        param.put("beginPos", page.getBeginPos());
        param.put("pageSize", page.getPageSize());
        List<ReleaseTask> releaseTaskList = releaseTaskMapper.getReleaseTaskListByMap(param);
        page.setRows(releaseTaskList);
        return page;
    }

    /**
     * 上传任务接口mytask（用户id，任务id，压缩包,保存自己的服务器时间,保存url【添加到building_task_record表】）
     * 更新building_release_task表中的updateUrl
     *
     * @param taskId
     * @param userId
     * @param url
     * @param nowDate
     * @return
     */
    @Override
    @Transactional
    public boolean uploadUserTask(Integer taskId, Integer userId, String url, Date nowDate) {
        log.info("访问的压缩包文件路径为:" + url);
        //更新release_task表中的updateUrl,updateTime,State为3【先查再更新】
        ReleaseTask releaseTask = releaseTaskMapper.getReleaseTaskById(taskId);
        ReleaseTask releaseTask0 = new ReleaseTask();//用于事务回滚使用
        if (releaseTask != null) {
            //设置回滚的原来数据(一旦出错就回到原来的数据)
            releaseTask0.setId(releaseTask.getId());
            releaseTask0.setTaskName(releaseTask.getTaskName());
            releaseTask0.setTime(releaseTask.getTime());
            releaseTask0.setRemark(releaseTask.getRemark());
            releaseTask0.setUrl(releaseTask.getUrl());
            releaseTask0.setState(releaseTask.getState());
            releaseTask0.setUserId(releaseTask.getUserId());
            releaseTask0.setUpdateUrl(releaseTask.getUpdateUrl());
            releaseTask0.setUpdateTime(releaseTask.getUpdateTime());
            releaseTask0.setType(releaseTask.getType());
            //设置跟新数据
            releaseTask.setUpdateUrl(url);//设置上传任务路径
            releaseTask.setUpdateTime(nowDate);//设置任务上传时间
            releaseTask.setState(Constant.RELEASE_TASK_STATE_3);//设置状态为3 上传任务状态
        } else {
            log.info("找不到对应的任务，请检查任务id是否正确");
            return false;
        }
        //开始更新release_task
        int flag1 = releaseTaskMapper.updateReleaseTask(releaseTask);

        //添加到task_record作为记录
        TaskRecord taskRecord = new TaskRecord();
        taskRecord.setTaskId(taskId);
        taskRecord.setUserId(userId);
        taskRecord.setUrl(url);
        taskRecord.setUpdateTime(nowDate);
        taskRecord.setType(releaseTask.getType());

        int flag2 = taskRecordMapper.insertTaskRecord(taskRecord);

        //更新release_task失败，添加到task_record作为记录成功
        if (flag1 <= 0 && flag2 > 0) {
            log.info("更新release_task失败，开始回滚task_record中数据");
            //删除task_record中插入的数据
            //先查再删
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("taskId", taskId);
            params.put("userId", userId);
            params.put("updateTime", nowDate);
            List<TaskRecord> taskRecordList = taskRecordMapper.getTaskRecordListByMap(params);
            if (!taskRecordList.isEmpty()) {
                //获取id，删除
                Integer id = taskRecordList.get(0).getId();
                int num = taskRecordMapper.deleteTaskRecordById(id);
                if (num > 0) {
                    log.info("更新release_task失败,task_record数据回滚成功");
                } else {
                    log.info("更新release_task失败,task_record数据滚回失败");
                }
            } else {
                log.info("更新release_task失败,task_record数据回滚失败，未找到要回滚的数据");
            }
        }

        //更新release_task成功，添加到task_record作为记录失败
        if (flag1 > 0 && flag2 <= 0) {
            log.info("添加task_record失败，开始回滚release_task中数据");
            int num = releaseTaskMapper.updateReleaseTask(releaseTask0);
            if (num > 0) {
                log.info("添加task_record失败,release_task数据回滚成功");
            } else {
                log.info("添加task_record失败,release_task数据滚回失败");
            }
        }

        if (flag1 > 0 && flag2 > 0) {
            return true;
        }
        return false;
    }

}
